/*
 * File:         jpegview.c
 *
 * Description:  View jpegs on a frame buffer
 *
 * Modified:     Copyright 2006 Analog Devices Inc.
 *
 * Bugs:         Enter bugs at http://blackfin.uclinux.org/
 *
 * This program is free software ;  you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation ;  either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY ;  without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program ;  see the file COPYING.
 * If not, write to the Free Software Foundation,
 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <setjmp.h>
#if	defined _BF533
#include "Debug.h"
#include "FileSys.h"
#include "DrawTool.h"
#include "Memory.h"
#else
#include "../Common/debug.h"
#include "../Common/Memory.h"
#include "../Common/FileSys.h"
#include "../mmn/DrawTool.h"
#endif

#include "jpeglib.h"
#include "jpeg.h"

//#define	BF54X_UPGRADE

unsigned char *framebase = 0;

#ifndef BF54X_UPGRADE
unsigned long BufferWidth = 720, BufferHeight = 480 ;
#else
unsigned long BufferWidth = 600, BufferHeight = 360 ;
#endif
unsigned long ImageWidth, ImageHeight;
unsigned int  StartX, StartY;
unsigned int  RECTWIDTH, RECTHEIGHT;
unsigned int  RectTop, RectBottom, RectLeft, RectRight;
const TCanvas *canvas;
int ChFun ;
int BGColor;
int BGRcolor;
int BGGcolor;
int BGBcolor;
//#define RGB(r,g,b) (((b&0x1f)<<11)|((g&0x3f)<<5)|(r&0x1f))
//#define RGB(r,g,b) ~((((b&0xf8)<<8)|((g&0xfc)<<3)|(r>>3)))
//#define RGB(r,g,b) ((((r&0xf8)<<8)|((g&0xfc)<<3)|(b>>3)))
#define RGB(r,g,b) ((b<<16)|(g<<8)|(r))
#define RFUN	(0)
#define GFUN	(1)
#define BFUN	(2)

struct my_error_mgr {
	struct jpeg_error_mgr pub;/* "public" fields */
	
	jmp_buf setjmp_buffer;/* for return to caller */
};

typedef struct my_error_mgr * my_error_ptr;

/*
 * Here's the routine that will replace the standard error_exit method:
 */

void my_error_exit (j_common_ptr cinfo)
{
	/* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
	my_error_ptr myerr = (my_error_ptr) cinfo->err;
	
	/* Always display the message. */
	/* We could postpone this until after returning, if we chose. */
	(*cinfo->err->output_message) (cinfo);
	
	/* Return control to the setjmp point */
	longjmp(myerr->setjmp_buffer, 1);
}

void put_scanline_someplace_noscale(unsigned char *buffer, int row_width, unsigned long row)
{
//	unsigned char *pD;
	unsigned char *pS;
	unsigned char r, g, b;
	unsigned long start_x, start_y;

	if(row >= BufferHeight)
		return; 

//	if(ImageWidth < BufferWidth)
//		startx = (BufferWidth - ImageWidth)/2;
//	if(ImageHeight < BufferHeight)
//		starty = (BufferHeight - ImageHeight)/2;

//	pD = framebase + ((row+starty) * BufferWidth * 3);
	pS = buffer;
//	LOG("buffer %d, row %d, BufferWidth %d, ImageWith %d \n", pS, row, BufferWidth, ImageWidth);
	row_width=ImageWidth;

	if (ChFun == 2){
	StartY = RectTop + (RECTHEIGHT-ImageHeight)/2;
	StartX = RectLeft + (RECTWIDTH-ImageWidth)/2;
//	LOG("StartX %d, StartY %d\n", StartX, StartY);
	}

//	LOG("ChFun %d\n", ChFun);

	start_x=StartX;
	start_y=StartY;
//	while(startx--)
//		pD+=3;
	while(row_width--)
       	{
		if(row_width < BufferWidth)
	       	{
			r = *pS++;;
//			LOG("R %d", r);
			g = *pS++;;
//			LOG("G %d", g);
			b = *pS++;;
//			LOG("RGB(%d,%d,%d), ", r,g,b);
//			*pD++   = RGB(r,g,b);
			switch(ChFun){
				case 0:
				    g_DrawPixel(canvas, start_x++, start_y+row, RGB(r,g,b) );
				break;
				case 1:
					switch(BGColor){
						case RFUN:
							if( r < BGRcolor && g > BGGcolor && b > BGBcolor )	start_x++;
							else g_DrawPixel(canvas, start_x++, start_y+row, RGB(r,g,b) );
						break;
						case GFUN:
							if( r > BGRcolor && g < BGGcolor && b > BGBcolor )	start_x++;
							else g_DrawPixel(canvas, start_x++, start_y+row, RGB(r,g,b) );
						break;
						case BFUN:
							if( r > BGRcolor && g > BGGcolor && b < BGBcolor )	start_x++;
							else g_DrawPixel(canvas, start_x++, start_y+row, RGB(r,g,b) );
						break;
					}
				break;
				case 2:
					g_DrawPixel(canvas, start_x++, start_y+row, RGB(r,g,b) );
				break;
				case 3:
				break;
			}
		}
	}	
}

static unsigned long *ScaleTableX, *ScaleTableY;
static int FixScale = 1;

void put_scanline_someplace_scale(unsigned char *buffer, int row_width, unsigned long row)
{
	int i, y = -1;
	unsigned char *pS;
	unsigned short *pD, *pC;	
	unsigned char r, g, b;
	unsigned long startx=0, starty=0;

	for(i=0; i<ImageHeight;i++)
       	{
       		if(ScaleTableY[i] == row)
       		{
			y = i;
			break;
		}
	}

	if(y != -1)
	{
		if(ImageWidth < BufferWidth)
			startx = (BufferWidth - ImageWidth)/2;
		if(ImageHeight < BufferHeight)
			starty = (BufferHeight - ImageHeight)/2;

		pD = (unsigned short*)framebase + ((y+starty) * BufferWidth);
		while(startx--)
			pD++;
		for(i=0; i<ImageWidth; i++)
		{
			pS= buffer + (ScaleTableX[i]*3);
			if(pS > (buffer+row_width))
				break;
			r = *pS++;
			g = *pS++;
			b = *pS;
			// *pD++ = ((r<<7)&0x7c00) | ((g<<2)&0x03e0) | ((b>>3)&0x001f) | 0x8000;
			*pD++   = RGB(r,g,b);
		}

		pC = (unsigned short*)framebase + ((y+starty) * BufferWidth);

		for(i=y+1; i<ImageHeight;i++)
		{
			if(ScaleTableY[i] == row)
		       	{
				pD = (unsigned short*)framebase + ((i+starty) * BufferWidth);
				memcpy(pD, pC, BufferWidth*2);
			}
			else if(ScaleTableX[i] > row)
				break;
		}
	}
}

unsigned long div45(unsigned long num1, unsigned long num2)
{
	if((num1%num2) > (num2/2))
		return num1/num2+1;
	else
		return num1/num2;
}

void CreateScaleTable(int src_width, int src_height)
{
	int i;
	ScaleTableX= ut_malloc(ImageWidth * sizeof(unsigned long));
	ScaleTableY= ut_malloc(ImageHeight * sizeof(unsigned long));

	for(i=ImageWidth-1; i>=0; i--)
	{
		ScaleTableX[i] = div45(i * src_width, ImageWidth);
	}

	for(i=ImageHeight-1; i>=0; i--)
       	{
		ScaleTableY[i] = div45(i * src_height, ImageHeight);
	}
}

void ReleaseScaleTable(void)
{
	if(ScaleTableX)
		ut_free(ScaleTableX);
	if(ScaleTableY)
		ut_free(ScaleTableY);
	ScaleTableX = ScaleTableY = 0;
}


int read_JPEG_file (char * filename)
{
	/* This struct contains the JPEG decompression parameters and pointers to
	 * working space (which is allocated as needed by the JPEG library).
	 */
	struct jpeg_decompress_struct cinfo;
	/* We use our private extension JPEG error handler.
	 * Note that this struct must live as long as the main JPEG parameter
	 * struct, to avoid dangling-pointer problems.
	 */
	struct my_error_mgr jerr;
	/* More stuff */
	FILE * infile;/* source file */
	JSAMPARRAY buffer;/* Output row buffer */
	int row_stride;/* physical row width in output buffer */
	
	/* In this example we want to open the input file before doing anything else,
	 * so that the setjmp() error recovery below can assume the file is open.
	 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
	 * requires it in order to read binary files.
	 */
	
	if ((infile = fs_Open(filename, "rb")) == NULL) {
		fprintf(stderr, "can't open %s\n", filename);
		return 0;
	}

	/* Step 1: allocate and initialize JPEG decompression object */
	
	/* We set up the normal JPEG error routines, then override error_exit. */
	cinfo.err = jpeg_std_error(&jerr.pub);
	jerr.pub.error_exit = my_error_exit;
	/* Establish the setjmp return context for my_error_exit to use. */
	if (setjmp(jerr.setjmp_buffer)) {
		/* If we get here, the JPEG code has signaled an error.
		 * We need to clean up the JPEG object, close the input file, and return.
		 */
		jpeg_destroy_decompress(&cinfo);
		fclose(infile);
		return 0;
	}
	/* Now we can initialize the JPEG decompression object. */
	jpeg_create_decompress(&cinfo);
	
	/* Step 2: specify data source (eg, a file) */
	
	jpeg_stdio_src(&cinfo, infile);
	
	/* Step 3: read file parameters with jpeg_read_header() */
	
	(void) jpeg_read_header(&cinfo, TRUE);
	/* We can ignore the return value from jpeg_read_header since
	 *   (a) suspension is not possible with the stdio data source, and
	 *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
	 * See libjpeg.doc for more info.
	 */
	
	/* Step 4: set parameters for decompression */
	
	/* In this example, we don't need to change any of the defaults set by
	 * jpeg_read_header(), so we do nothing here.
	 */
	
	/* Step 5: Start decompressor */
	(void) jpeg_start_decompress(&cinfo);
	/* We can ignore the return value since suspension is not possible
	 * with the stdio data source.
	 */
	
	/* We may need to do some setup of our own at this point before reading
	 * the data.  After jpeg_start_decompress() we have the correct scaled
	 * output image dimensions available, as well as the output colormap
	 * if we asked for color quantization.
	 * In this example, we need to make an output work buffer of the right size.
	 */ 
	/* JSAMPLEs per row in output buffer */
	row_stride = cinfo.output_width * cinfo.output_components;
	/* Make a one-row-high sample array that will go away when done with image */
	buffer = (*cinfo.mem->alloc_sarray)
		((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
	
	/* Step 6: while (scan lines remain to be read) */
	/*           jpeg_read_scanlines(...); */
	
	/* Here we use the library's state variable cinfo.output_scanline as the
	 * loop counter, so that we don't have to keep track ourselves.
	 */

	ImageWidth = cinfo.output_width;
	ImageHeight = cinfo.output_height;
	if(FixScale)
       	{
		if(((double)ImageWidth/(double)ImageHeight) > ((double)BufferWidth/(double)BufferHeight))
	       	{
			ImageHeight = (unsigned long)((double)ImageHeight*(double)BufferWidth/(double)ImageWidth);
			ImageWidth = BufferWidth;
		}
		else
	       	{
			ImageWidth = (unsigned long)((double)ImageWidth*(double)BufferHeight/(double)ImageHeight);
			ImageHeight = BufferHeight;
		}
		CreateScaleTable(cinfo.output_width, cinfo.output_height);
		//printf("ImageWidth=%ld ImageHeight=%ld\n", ImageWidth, ImageHeight);
	}

	while (cinfo.output_scanline < cinfo.output_height) {
//	while (cinfo.output_scanline < 1) {
		/* jpeg_read_scanlines expects an array of pointers to scanlines.
		 * Here the array is only one element long, but you could ask for
		 * more than one scanline at a time if that's more convenient.
		 */
		(void) jpeg_read_scanlines(&cinfo, buffer, 1);
		/* Assume put_scanline_someplace wants a pointer and sample count. */
		if(FixScale)
			put_scanline_someplace_scale(buffer[0], row_stride, cinfo.output_scanline-1);
		else
			put_scanline_someplace_noscale(buffer[0], row_stride, cinfo.output_scanline-1);
//			put_scanline_someplace_noscale(buffer[0], 1, 1);
	}

	if(FixScale)
		ReleaseScaleTable();

	/* Step 7: Finish decompression */
	
	(void) jpeg_finish_decompress(&cinfo);
	/* We can ignore the return value since suspension is not possible
	 * with the stdio data source.
	 */
	
	/* Step 8: Release JPEG decompression object */
	
	/* This is an important step since it will release a good deal of memory. */
	jpeg_destroy_decompress(&cinfo);
	
	/* After finish_decompress, we can close the input file.
	 * Here we postpone it until after no more JPEG errors are possible,
	 * so as to simplify the setjmp error logic above.  (Actually, I don't
	 * think that jpeg_destroy can do an error exit, but why assume anything...)
	 */
	fs_Close(&infile);
	
	/* At this point you may want to check to see whether any corrupt-data
	 * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
	 */
	
	/* And we're done! */
	return 1;
}

//int DrawJpeg(const TCanvas *canv, unsigned char *BufferPtr, unsigned long Width, unsigned long Height, int x, int y, char * filename)
TJpeg DrawJpeg(const TCanvas *canv, int x, int y, char * filename)
{
	TJpeg Jpeg;
	canvas = canv;
	StartX = x;
	StartY = y;
//	LOG("BufferWidth = %ld BufferHeight = %ld\n", BufferWidth, BufferHeight);
	FixScale = 0;
	ChFun = 0;
	
	if(read_JPEG_file(filename))
	{
		Jpeg.Width = ImageWidth;
		Jpeg.Height = ImageHeight;
		//LOG("read %s OK, W %d, H %d\n", filename, ImageWidth, ImageHeight);
		return Jpeg;
	}
	else
	{
		Jpeg.Width = ImageWidth = 0;
		Jpeg.Height = ImageHeight = 0;
		LOG("read %s FAIL, W %d, H %d\n", filename, ImageWidth, ImageHeight);
		
		return Jpeg;
	}
}

TJpeg DrawJpegRemBG(const TCanvas *canv, int x, int y, char * filename, int RGB_R, int RGB_G, int RGB_B )
{
	TJpeg Jpeg;
	canvas = canv;
	StartX = x;
	StartY = y;
	FixScale = 0;
	ChFun = 1;

	if( RGB_R == 0 ){
		BGRcolor = RGB_R + 55;
		BGColor = RFUN;
	}else BGRcolor = RGB_R - 55;

	if( RGB_G == 0 ){
		BGGcolor = RGB_G + 55;
		BGColor = GFUN;
	}else BGGcolor = RGB_G - 55;

	if( RGB_B == 0 ){
		BGBcolor = RGB_B + 55;
		BGColor = BFUN;
	}else BGBcolor = RGB_B - 55;


	if(read_JPEG_file(filename))
	{
		Jpeg.Width = ImageWidth;
		Jpeg.Height = ImageHeight;
		//LOG("read %s OK\n", filename);
		return Jpeg;
	}
	else
	{
				Jpeg.Width = ImageWidth = 0;
		Jpeg.Height = ImageHeight = 0;
		LOG("read %s FAIL\n", filename);
		return Jpeg;
	}
}

TJpeg DrawJpegCenter(const TCanvas *canv, TRect *rect, char * filename)
{
		TJpeg Jpeg;
	canvas = canv;

	RectTop = rect->top;
	RectBottom = rect->bottom;
	RectLeft = rect->left;
    RectRight = rect->right;

	RECTHEIGHT = (RectBottom - RectTop + 1) ;
	RECTWIDTH = (RectRight - RectLeft + 1) ;
	
	LOG("%d %d %d %d\n", RectTop, RectBottom, RectLeft, RectRight);

	LOG("BufferWidth = %ld BufferHeight = %ld\n", BufferWidth, BufferHeight);
	FixScale = 0;
	ChFun = 2;

	if(read_JPEG_file(filename))
	{
		Jpeg.Width = ImageWidth;
		Jpeg.Height = ImageHeight;
		return Jpeg;
	}
	else
	{
				Jpeg.Width = ImageWidth = 0;
		Jpeg.Height = ImageHeight = 0;
		LOG("read %s FAIL, W %d, H %d\n", filename, ImageWidth, ImageHeight);
		return Jpeg;
	}
}

TJpeg GetJpegPtr(char * filename)
{
	TJpeg Jpeg;
	ChFun = 3;
	if(read_JPEG_file(filename))
	{
		Jpeg.Width = ImageWidth;
		Jpeg.Height = ImageHeight;
		//LOG("read %s OK, W %d, H %d\n", filename, ImageWidth, ImageHeight);
		return Jpeg;
	}
	else
	{
		Jpeg.Width = ImageWidth = 0;
		Jpeg.Height = ImageHeight = 0;
		LOG("read %s FAIL, W %d, H %d\n", filename, ImageWidth, ImageHeight);
		return Jpeg;
	}
}

int read_JPEG_res (char *pbuffer)
{
	/* This struct contains the JPEG decompression parameters and pointers to
	 * working space (which is allocated as needed by the JPEG library).
	 */
	struct jpeg_decompress_struct cinfo;
	/* We use our private extension JPEG error handler.
	 * Note that this struct must live as long as the main JPEG parameter
	 * struct, to avoid dangling-pointer problems.
	 */
	struct my_error_mgr jerr;
	/* More stuff */
//	FILE * infile;/* source file */
	JSAMPARRAY buffer;/* Output row buffer */
	int row_stride;/* physical row width in output buffer */
	
	/* In this example we want to open the input file before doing anything else,
	 * so that the setjmp() error recovery below can assume the file is open.
	 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
	 * requires it in order to read binary files.
	 */

	if ( pbuffer == NULL) {
//		fprintf(stderr, "can't open %s\n", filename);
		return 0;
	}

//	file_size = _filelength(_fileno(fp));
//	pbuf = (char*) malloc(file_size+1);
//	memset( pbuf, 0, file_size+1 );
//	fread(pbuf, file_size, 1, fp);

	/* Step 1: allocate and initialize JPEG decompression object */
	
	/* We set up the normal JPEG error routines, then override error_exit. */
	cinfo.err = jpeg_std_error(&jerr.pub);
	jerr.pub.error_exit = my_error_exit;
	/* Establish the setjmp return context for my_error_exit to use. */
	if (setjmp(jerr.setjmp_buffer)) {
		/* If we get here, the JPEG code has signaled an error.
		 * We need to clean up the JPEG object, close the input file, and return.
		 */
		jpeg_destroy_decompress(&cinfo);
//		fclose(infile);
		return 0;
	}
	/* Now we can initialize the JPEG decompression object. */
	jpeg_create_decompress(&cinfo);
	
	/* Step 2: specify data source (eg, a file) */
	
	jpeg_stdio_src_buffer(&cinfo, pbuffer);
	
	/* Step 3: read file parameters with jpeg_read_header() */
	
	(void) jpeg_read_header(&cinfo, TRUE);
	/* We can ignore the return value from jpeg_read_header since
	 *   (a) suspension is not possible with the stdio data source, and
	 *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
	 * See libjpeg.doc for more info.
	 */
	
	/* Step 4: set parameters for decompression */
	
	/* In this example, we don't need to change any of the defaults set by
	 * jpeg_read_header(), so we do nothing here.
	 */
	
	/* Step 5: Start decompressor */
	(void) jpeg_start_decompress(&cinfo);
	/* We can ignore the return value since suspension is not possible
	 * with the stdio data source.
	 */
	
	/* We may need to do some setup of our own at this point before reading
	 * the data.  After jpeg_start_decompress() we have the correct scaled
	 * output image dimensions available, as well as the output colormap
	 * if we asked for color quantization.
	 * In this example, we need to make an output work buffer of the right size.
	 */ 
	/* JSAMPLEs per row in output buffer */
	row_stride = cinfo.output_width * cinfo.output_components;
	/* Make a one-row-high sample array that will go away when done with image */
	buffer = (*cinfo.mem->alloc_sarray)
		((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
	
	/* Step 6: while (scan lines remain to be read) */
	/*           jpeg_read_scanlines(...); */
	
	/* Here we use the library's state variable cinfo.output_scanline as the
	 * loop counter, so that we don't have to keep track ourselves.
	 */

	ImageWidth = cinfo.output_width;
	ImageHeight = cinfo.output_height;
	if(FixScale)
       	{
		if(((double)ImageWidth/(double)ImageHeight) > ((double)BufferWidth/(double)BufferHeight))
	       	{
			ImageHeight = (unsigned long)((double)ImageHeight*(double)BufferWidth/(double)ImageWidth);
			ImageWidth = BufferWidth;
		}
		else
	       	{
			ImageWidth = (unsigned long)((double)ImageWidth*(double)BufferHeight/(double)ImageHeight);
			ImageHeight = BufferHeight;
		}
		CreateScaleTable(cinfo.output_width, cinfo.output_height);
		//printf("ImageWidth=%ld ImageHeight=%ld\n", ImageWidth, ImageHeight);
	}

	while (cinfo.output_scanline < cinfo.output_height) {
//	while (cinfo.output_scanline < 1) {
		/* jpeg_read_scanlines expects an array of pointers to scanlines.
		 * Here the array is only one element long, but you could ask for
		 * more than one scanline at a time if that's more convenient.
		 */
		(void) jpeg_read_scanlines(&cinfo, buffer, 1);
		/* Assume put_scanline_someplace wants a pointer and sample count. */
		if(FixScale)
			put_scanline_someplace_scale(buffer[0], row_stride, cinfo.output_scanline-1);
		else
			put_scanline_someplace_noscale(buffer[0], row_stride, cinfo.output_scanline-1);
//			put_scanline_someplace_noscale(buffer[0], 1, 1);
	}

	if(FixScale)
		ReleaseScaleTable();

	/* Step 7: Finish decompression */
	
	(void) jpeg_finish_decompress(&cinfo);
	/* We can ignore the return value since suspension is not possible
	 * with the stdio data source.
	 */
	
	/* Step 8: Release JPEG decompression object */
	
	/* This is an important step since it will release a good deal of memory. */
	jpeg_destroy_decompress(&cinfo);
	
	/* After finish_decompress, we can close the input file.
	 * Here we postpone it until after no more JPEG errors are possible,
	 * so as to simplify the setjmp error logic above.  (Actually, I don't
	 * think that jpeg_destroy can do an error exit, but why assume anything...)
	 */
//	fs_Close(&infile);
	
	/* At this point you may want to check to see whether any corrupt-data
	 * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
	 */
	
	/* And we're done! */
	return 1;
}

TJpeg DrawJpegBuf(const TCanvas *canv, int x, int y, char *pbuffer)
{
	TJpeg Jpeg;
	canvas = canv;
	StartX = x;
	StartY = y;
	FixScale = 0;
	ChFun = 0;

	if(read_JPEG_res(pbuffer))
	{
		Jpeg.Width = ImageWidth;
		Jpeg.Height = ImageHeight;
		LOG("$$$read buffer OK$$$\n");
		return Jpeg;
	}
	else
	{
		Jpeg.Width = ImageWidth = 0;
		Jpeg.Height = ImageHeight = 0;
		LOG("*** read buffer FAIL!!***\n");
		return Jpeg;
	}

}

TJpeg GetJpegPtrBuf(char *jpbuffer)
{
	TJpeg Jpeg;
	ChFun = 3;
	if(read_JPEG_res(jpbuffer))
	{
		Jpeg.Width = ImageWidth;
		Jpeg.Height = ImageHeight;
		//LOG("read jpbuffer OK, W %d, H %d\n", ImageWidth, ImageHeight);
		return Jpeg;
	}
	else
	{
		Jpeg.Width = ImageWidth = 0;
		Jpeg.Height = ImageHeight = 0;
		LOG("read jpbuffer FAIL, W %d, H %d\n", ImageWidth, ImageHeight);
		return Jpeg;
	}
}

TJpeg DrawJpegBufRmBG(const TCanvas *canv, int x, int y, char *jpbuffer, int RGB_R, int RGB_G, int RGB_B )
{
	TJpeg Jpeg;
	canvas = canv;
	StartX = x;
	StartY = y;
	FixScale = 0;
	ChFun = 1;

	if( RGB_R == 0 ){
		BGRcolor = RGB_R + 75;
		BGColor = RFUN;
	}else BGRcolor = RGB_R - 155;

	if( RGB_G == 0 ){
		BGGcolor = RGB_G + 75;
		BGColor = GFUN;
	}else BGGcolor = RGB_G - 155;

	if( RGB_B == 0 ){
		BGBcolor = RGB_B + 75;
		BGColor = BFUN;
	}else BGBcolor = RGB_B - 155;
	
	if(read_JPEG_res(jpbuffer))
	{
		Jpeg.Width = ImageWidth;
		Jpeg.Height = ImageHeight;
//		LOG("DrawJpegBufRmBG OK\n");
		return Jpeg;
	}
	else
	{
		Jpeg.Width = ImageWidth = 0;
		Jpeg.Height = ImageHeight = 0;
		LOG("DrawJpegBufRmBG Fail\n");
		return Jpeg;
	}
}
